package com.ronan.common.protocol;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import com.ronan.common.utils.RIMCommandManager;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.Data;

/**
 * FileName    : com.ronan.imserver.protocol
 * Description :
 *
 * @author : ysk
 * @version : 1.0
 * Create Date : 2021/2/26 0:18
 **/
@Data
public class RIMProtocol implements IRIMProtocol {

    private RIMHeader header;

    private MessageLite body;

    /**
     * 编码
     *
     * @param buf 缓冲区
     */
    public void encode(ByteBuf buf) {
        header.encode(buf);
        buf.writeBytes(body.toByteArray());
    }

    /**
     * 解码
     *
     * @param buf 缓冲区
     * @throws InvalidProtocolBufferException 无效的协议缓冲区例外
     */
    public void decode(ByteBuf buf) throws InvalidProtocolBufferException {

        RIMHeader header = new RIMHeader();
        header.decode(buf);
        this.header = header;

        // command
        int command = header.getCommand();
        // 根据command获取body的数据类型
        MessageLite body = RIMCommandManager.getBodyByCommand(command);

        // 解码body
        final byte[] array;
        final int offset;
        final int length = buf.readableBytes();

        if (buf.hasArray()) {
            array = buf.array();
            offset = buf.arrayOffset() + buf.readerIndex();
        } else {
            array = ByteBufUtil.getBytes(buf, buf.readerIndex(), length, false);
            offset = 0;
        }
        this.body = body.getParserForType().parseFrom(array, offset, length);
    }
}
